package com.yingsheng.bi.hks.template.controller.processor;

import com.yingsheng.bi.hks.template.events.Event;
import com.yingsheng.bi.hks.template.events.HandlerMethodEvent;
import com.yingsheng.bi.hks.template.processor.InnerProcessor;
import com.yingsheng.bi.hks.template.utils.JacksonUtils;

import java.util.Map;

public class JsonRequestBodyProcessor extends InnerProcessor {

    @Override
    public void execInner(Event event) {
        if (event instanceof HandlerMethodEvent) {
            HandlerMethodEvent handlerMethodEvent = (HandlerMethodEvent) event;
            Object input = handlerMethodEvent.getInput();
            if (input != null && input instanceof String) {
                String jsonBody = (String) input;
                Map<String, Object> bodyMap = JacksonUtils.json2Map(jsonBody);
                event.putAll(bodyMap);
                super.execInner(event);
                Object output = handlerMethodEvent.getOutput();
                if (output != null) {
                    if (!(output instanceof String)) {
                        handlerMethodEvent.setOutput(JacksonUtils.obj2Json(output));
                    }
                }
            } else {
                super.execInner(event);
            }
        } else {
            super.execInner(event);
        }
    }
}
